<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
      <BasicForm @register="registerForm" @eventFormModel="eventFormModel">
        <template #formFooter>
            <h2 style="font-size:16px;" v-if="dataSource.length">成本计算器</h2>
            <a-table style="width:100%" bordered :dataSource="dataSource" v-if="dataSource.length" :columns="columnss" :pagination="false">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'totalCost'">
                        {{ record.totalCost ? parseFloat(record.totalCost).toFixed(0) : 0 }}
                    </template>
                    <template v-if="column.key === 'totalAmount'">
                        {{ record.totalAmount ? parseFloat(record.totalAmount).toFixed(0) : 0 }}
                    </template>
                    <template v-if="column.key === 'remainderBudget'">
                        {{ record.remainderBudget ? parseFloat(record.remainderBudget).toFixed(0) : 0 }}
                    </template>
                    <template v-if="column.key === 'currentMonthConsume'">
                        {{ record.currentMonthConsume ? parseFloat(record.currentMonthConsume).toFixed(0) : 0 }}
                    </template>
                    <template v-if="column.key === 'costStatus'">
                        <a-tag v-if="record.costStatus == 1" color="green">正常</a-tag>
                        <a-tag v-if="record.costStatus == 2" color="orange">接近阈值</a-tag>
                        <a-tag v-if="record.costStatus == 3" color="red">接近预警值</a-tag>
                    </template>
                </template>
            </a-table>
        </template>
        <template #hrId="{model, field}">
            <a-input-search
            v-model:value="model[field]"
            placeholder="请选择人员"
            enter-button="人员选择"
            size="size"
            @search="getUser"
            :disabled="!def.projectId"
            />
        </template>
      </BasicForm>
      <VerifyInfo :verifyType="5" ref="childRef"/>
    </BasicModal>
    <a-modal v-model:visible="visible" title="人员选择" :width="1100" :zIndex="1001" @ok="userOk">
        <div style="padding:15px">
            <div class="hed">
                <span style="flex: 0.2;">&nbsp;</span>
                <span v-for="h in userColumns">{{ h.title }}</span>
            </div>
            <div class="cont">
                <ul v-for="cont in userData">
                    <li style="flex: 0.2;">
                        <span>
                            <a-checkbox v-model:checked="cont.checked"></a-checkbox>
                        </span>
                    </li>
                    <li>
                        <span>{{ cont.name }}</span>
                    </li>
                <!--    <li>
                        <span>{{ cont.cost }}</span>
                    </li>-->
                    <li>
                        <a-date-picker format="YYYY-MM-DD" v-model:value="cont.startTime" />
                    </li>
                    <li>
                        <a-date-picker format="YYYY-MM-DD" v-model:value="cont.endTime" />
                    </li>
                    <li>
                        <a-input v-model:value="cont.usePercent" placeholder="请输入" suffix="%"/>
                    </li>
                    <li>
                        <a-textarea v-model:value="cont.content" placeholder="请输入" />
                    </li>
                    <li>
                        <a-tooltip placement="top" :title="cont.remark">
                            <span class="media-box__desc">{{ cont.remark }}</span>
                        </a-tooltip>
                    </li>
                </ul>
            </div>
        </div>
    </a-modal>
    <a-modal v-model:visible="msgVisible" title="确认提交" @ok="handleOk">
      <div style="text-align: center;padding:20px; font-size:15px">
        {{ errMsg }}
      </div>
    </a-modal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref, reactive} from 'vue';
    import dayjs from 'dayjs'
    import businessDays from 'dayjs-business-days'
    import { useMessage } from '/@/hooks/web/useMessage';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import VerifyInfo from './verifyInfo.vue'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../MonsterHrCostSubmit.data';
    import {saveOrUpdate, queryStaffList, queryVerify} from '../MonsterHrCostSubmit.api';
    import {queryCurrentCostBudget, queryStaffBySubmitId} from '../MonsterSupplierCostSubmit.api';
    import { USER_INFO_KEY } from '/@/enums/cacheEnum'
    import { getAuthCache } from '/@/utils/auth'
    import { countStatus, countStatusHr, dateMonths, notEmpty } from '/@/utils/tool'
    const { createMessage } = useMessage()
    let user:any = getAuthCache(USER_INFO_KEY) || {}
    let items:any = ref({})
    const defStaffInfo:any = ref([])
    const childRef = ref()
    const msgVisible = ref(false)
    const errMsg = ref()
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const visible = ref(false)
    let oId = ''
    const userColumns = ref([
        {
            title: '姓名',
            dataIndex: 'name',
        },
       /* {
            title: '成本',
            dataIndex: 'salaryMoney',
        },*/
        {
            title: '开始时间',
            dataIndex: 'socialSecurity',
        },
        {
            title: '结束时间',
            dataIndex: 'accumulationFund',
        },
        {
            title: '工作量',
            dataIndex: 'accumulationFund',
        },
        {
            title: '工作内容',
            dataIndex: 'accumulationFund',
        },
        {
            title: '工作量描述',
            dataIndex: 'accumulationFund',
        },
    ])
    const userData = ref([])
    const def = ref({})
    const staffInfo = ref<any>([])
    const checkedVal = ref([])
    const isType = ref('add')

    const dataSource = ref<any>([])
    const dataOldSource = ref<any>('')
    const columnss = ref([
        {
            title: '人力成本总额',
            dataIndex: 'totalCost',
            key: 'totalCost',
        },
        {
            title: '已使用总额',
            dataIndex: 'totalAmount',
            key: 'totalAmount',
        },
        {
            title: '剩余总额',
            dataIndex: 'remainderBudget',
            key: 'remainderBudget',
        },
        {
            title: '剩余可支配月费',
            dataIndex: 'currentMonthConsume',
            key: 'currentMonthConsume',
        },
        // {
        //     title: '当前预算状态',
        //     dataIndex: 'costStatus',
        //     key: 'costStatus',
        // },
    ])
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        dataSource.value = []
        dataOldSource.value = ''
        isType.value = data.isType
        defStaffInfo.value = []
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        oId = ''
        if (unref(isUpdate)) {
            items.value = data.record
            childRef.value.childMethod(data.record)
            queryStaffBySubmitIdFun(data.record)
            await list(data.record)
            //表单赋值
            await setFieldsValue({
                ...data.record,
            })
        }else {
            childRef.value.childMethod()
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            if(!notEmpty(values, ['projectId', 'totalHrAmount','hrId'])) {
                return createMessage.warn('请完善信息')
            }
            if( dataSource.value[0].remainderBudget <0) {
                return createMessage.warn('申请额度超出预算，无法提交')
            }

            // 超过150 限制
            // let v = await queryVerify(Object.assign(values,{staffInfo: JSON.stringify(staffInfo.value),status:1}))

            // if(v && v.code == 200 && v.message) {
            //     errMsg.value = v.message
            //     msgVisible.value = true
            //     return
            // }

            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{staffInfo: JSON.stringify(staffInfo.value),status:1}), isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    // 超过150 限制
    async function handleOk() {
        msgVisible.value = false
        try {
            let values = await validate();
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{staffInfo: JSON.stringify(staffInfo.value),status:1}), isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    // 获取人员信息
    async function queryStaffBySubmitIdFun(item) {
        let r = await queryStaffBySubmitId({submitId:item.id})
        defStaffInfo.value = r
    }

    async function list (item) {
        let res = await queryCurrentCostBudget({operateType:2,submitType:2,projectId:item.projectId,id:item.id,payAmount: item.totalHrAmount ? item.totalHrAmount : 0})//.then(res => {
            dataSource.value = [res]
            dataOldSource.value = JSON.stringify(res)
            dataSource.value[0].payAmount = item.totalHrAmount ? item.totalHrAmount : 0
        // })
    }

    function getUser () {
        staffList()
        visible.value = true
    }

    function workDays(startDate, endDate) {
        const start = new Date(startDate);
        const end = new Date(endDate);
        let wd = 0;
        let current = start;

        while (current <= end) {
            // 排除周六和周日
            if (current.getDay() !== 0 && current.getDay() !== 6) {
                wd++;
            }
            current.setDate(current.getDate() + 1);
        }

        return wd;
    }

    function userOk (e) {
        let arr = JSON.parse(JSON.stringify(userData.value))
        let z:any = []
        let name:any = []
        let time:any = []
        let bfb = 0
        let tips:any = []
        let totalcost = 0;
        dayjs.extend(businessDays);

        const startOfYear = dayjs().startOf('year');
        const endOfYear = dayjs().endOf('year');

        // 计算工作日天数
        const workdaysCount = dayjs(endOfYear).businessDiff(startOfYear);
        arr.forEach((item:any) => {
            if(item.checked) {
                let start = dayjs(item.startTime).format('YYYY-MM-DD')
                let end = dayjs(item.endTime).format('YYYY-MM-DD')
                const ds = workDays(start,end)//dayjs(date2).businessDiff(dayjs(date1));

                // let m = dateMonths(dayjs(item.startTime).format('YYYY-MM-DD'), dayjs(item.endTime).format('YYYY-MM-DD'))
                let dy = Math.abs(workdaysCount) // - 11
                // 总薪水 /（年工作总天数） * （开始时间 - 结束时间 工作日天数） *30%
                let n = Number(item.salaryMoney * 12)  / Number(dy) * (Number(Math.abs(ds)) * (item.usePercent / 100)) //工资 * 月数  * 30%
                 n = n.toFixed(0);
                checkedVal.value.push(n)
                bfb += Number(item.usePercent);
                z.push(n)
                name.push(item.name)
                staffInfo.value.push({
                    staffId: item.id,
                    cost: n,
                    usePercent: (item.usePercent / 100),
                    beginTime: item.startTime,
                    endTime: item.endTime,
                    content: item.content
                })
                if((!item.startTime || item.startTime == null) || (!item.endTime || item.endTime == null)) {
                    time.push(item.name)
                }

                if(item.usePercent >=100) {
                    tips.push({
                        staffId: item.id,
                        cost: n,
                        usePercent: item.usePercent,
                        beginTime: item.startTime,
                        endTime: item.endTime,
                        content: item.content
                    })
                }

                defStaffInfo.value.push(Object.assign(item,{staffId:item.id, usePercent: (item.usePercent / 100)}))
            }
        })
        console.log('bfb', tips)
        if(time.length <=0) {
            visible.value = false
        } else {
            return createMessage.warn(time.join(',') + '开始时间或结束时间不能为空')
        }
        // 总成本计算
        // visible.value = false

      const sum = z.reduce((prev, cur, index, z) => {
            return Number(prev) +  Number(cur)
        }, 0)
        setFieldsValue({ totalHrAmount: Number(sum).toFixed(0), hrId: name.join(' ') })
    }

    function staffList () {
        queryStaffList().then(res => {
            staffInfo.value = []
            let r = res
            let defArr = defStaffInfo.value
            r.map((item:any) => {
                let cost = Number(item.salaryMoney)
                item.cost = cost
                defArr.forEach((df:any) => {
                    if(item.id === df.staffId) {
                        // item.cost = df.cost
                        item.startTime = dayjs(df.startTime)
                        item.endTime = dayjs(df.endTime)
                        item.usePercent = parseInt(df.usePercent * 100)
                        item.content = df.content
                        item.checked = true
                    }
                })
            })
            userData.value = r
        })
    }

    async function eventFormModel (e) {
        if(isType.value =='info') {
            setTimeout(() => {
                isType.value = 'add'
            },1000)
            return
        }
        def.value = e
        items.value = e
        if(e && e.projectId && oId != e.projectId) {
            oId = e.projectId
            await list(e)
        }

        if(dataSource.value.length) {


            countStatusHr(1,dataSource.value,dataOldSource.value,e.totalHrAmount)

            // let cost = (Number(dataSource.value[0].currentAvablieCost) - Number(dataSource.value[0].currentMonthConsume) - Number(e.totalHrAmount)) / Number(dataSource.value[0].currentAvablieCost)
            // if(cost < dataSource.value[0].remindThreshold && cost > dataSource.value[0].warningThreshold) {
            //     dataSource.value[0].costStatus = 2
            // }
            // else if(cost < dataSource.value[0].warningThreshold) {
            //     dataSource.value[0].costStatus = 3
            // }
            // else {
            //     dataSource.value[0].costStatus = 1
            // }


            dataSource.value[0].payAmount = Number(e.totalHrAmount).toFixed(0)
        }
        if(!e.totalHrAmount && dataSource.value.length) {
            dataSource.value[0].payAmount = ''
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}

    .hed{
        display: flex;
        border: 1px solid #e5e7eb;
        background: #FAFAFA;
        border-bottom: 0;
        span{
            flex: 1;
            border-right: 1px solid #f0f0f0;
            padding: 12px 8px;
        }
    }
    .cont{
        border-bottom: 1px solid #e5e7eb;
        ul{
            display: flex;
            border: 1px solid #e5e7eb;
            margin: 0;
            border-bottom: 0;
        }
        li{
            flex: 1;
            border-right: 1px solid #f0f0f0;
            padding: 12px 8px;
        }
    }
    .media-box__desc {
        color: rgba(0,0,0,0.3);
        color: var(--weui-FG-2);
        font-size: 14px;
        line-height: 1.4;
        padding-top: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        word-wrap: break-word;
        -webkit-hyphens: auto;
        hyphens: auto;
        padding-left: 0;
    }
</style>
